﻿using HBS.InvokeSupport;
using IWshRuntimeLibrary;
using PIMS.Base;
using PIMS.DBModel;
using PIMS.ORM;
using PIMS.Utils;
using PIMS.XmlModel;
using PIMS_Interface.DBModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using File = System.IO.File;

namespace PIMS
{
    public partial class FormContainer : Form
    {
        string exitMsg = "";
        string basePath = AppDomain.CurrentDomain.BaseDirectory;
        string plant = "";
        string consumer = "";

        #region Form
        static FormLogView formLogView = new FormLogView() {
            TabText = "实时日志",
            CloseButton = false
        };
        static FormPLCStatePanel formPLCPanel1 = new FormPLCStatePanel()
        {
            TabText = "PLC状态",
            CloseButton = false
        };
        static FormMain formCurrent = new FormMain()
        {
            TabText = "当前工单",
            CloseButton = false
        };
        static FormHistory formHistory = new FormHistory()
        {
            TabText = "历史工单",
            CloseButton = false
        };
        static FormSavedDataBag formSavedData = new FormSavedDataBag()
        {
            TabText = "生产记录(袋)",
            CloseButton = false
        };
        static FormSavedData formSavedDataBox = new FormSavedData()
        {
            TabText = "生产记录(箱/托)",
            CloseButton = false
        };
        static FormLogHistory formLogHistory = new FormLogHistory()
        {
            TabText = "历史日志查询",
            CloseButton = false
        };
        #endregion

        private DeserializeDockContent m_deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString);

        public FormContainer()
        {
            InitializeComponent();

            SetFormMax(this);

            //使用WeifenLuo.WinFormsUI.Docking.dll
            this.dockPanel1.DockLeftPortion = 0.15d; //改变停靠大小
            this.dockPanel1.AllowEndUserDocking = false;
            this.dockPanel1.AllowEndUserNestedDocking = false;
            this.dockPanel1.Theme = new VS2015BlueTheme();

            if (Common.pimsConfig.GetAppValueByKey("init_DB") == "1")
            {
                DialogResult dr = MessageBox.Show("确认初始化数据库吗？\r\n该功能会自动建新数据库！\r\n请确保新库不存在，否则会出现重复数据！",
                    "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dr == DialogResult.Yes)
                {
                    try
                    {
                        var sqlSugarClient = SqlSugarHelper.GetDb();

                        #region 创建数据库和表的语句仅执行一次
                        //创建数据库
                        sqlSugarClient.DbMaintenance.CreateDatabase();
                        //创建表 varchar[50]
                        sqlSugarClient.CodeFirst.SetStringDefaultLength(50).InitTables(typeof(batchInfoSync));
                        sqlSugarClient.CodeFirst.SetStringDefaultLength(50).InitTables(typeof(datadictionary));
                        sqlSugarClient.CodeFirst.SetStringDefaultLength(50).InitTables(typeof(orderformcurrent));
                        sqlSugarClient.CodeFirst.SetStringDefaultLength(50).InitTables(typeof(orderformhistory));
                        sqlSugarClient.CodeFirst.SetStringDefaultLength(50).InitTables(typeof(saveddata));
                        sqlSugarClient.CodeFirst.SetStringDefaultLength(50).InitTables(typeof(saveddataBag));
                        sqlSugarClient.CodeFirst.SetStringDefaultLength(50).InitTables(typeof(users));
                        sqlSugarClient.CodeFirst.SetStringDefaultLength(50).InitTables(typeof(SerialNum));

                        List<orderformcurrent> listCurrnet = sqlSugarClient.Queryable<orderformcurrent>().ToList();
                        if (listCurrnet.Count == 0)
                        {
                            string[] deviceNames = Common.pimsConfig.GetAppValueByKey("deviceName").Split('|');
                            for (int i = 0; i < deviceNames.Length; i++)
                            {
                                //新增一条记录
                                sqlSugarClient.Insertable<orderformcurrent>(new orderformcurrent()
                                {
                                    id = i + 1,
                                    packager = deviceNames[i]
                                }).ExecuteCommand();
                            }
                        }

                        List<users> listusers = sqlSugarClient.Queryable<users>().ToList();
                        if (listusers.Count == 0)
                        {
                            //新增一条记录
                            sqlSugarClient.Insertable<users>(new users()
                            {
                                ID = 1,
                                UserName = "Admin",
                                Password = "admin",
                                Description = "管理员",
                                Department = "管理",
                                Level = "9"
                            }).ExecuteCommand();
                            sqlSugarClient.Insertable<users>(new users()
                            {
                                ID = 2,
                                UserName = "包装A",
                                Password = "A123",
                                Description = "操作员",
                                Department = "A",
                                Level = "1"
                            }).ExecuteCommand();
                            sqlSugarClient.Insertable<users>(new users()
                            {
                                ID = 3,
                                UserName = "包装B",
                                Password = "B123",
                                Description = "操作员",
                                Department = "B",
                                Level = "1"
                            }).ExecuteCommand();
                            sqlSugarClient.Insertable<users>(new users()
                            {
                                ID = 4,
                                UserName = "包装C",
                                Password = "C123",
                                Description = "操作员",
                                Department = "C",
                                Level = "1"
                            }).ExecuteCommand();
                        }

                        List<SerialNum> listSerialNum = sqlSugarClient.Queryable<SerialNum>().ToList();
                        if(listSerialNum.Count == 0)
                        {
                            //新增一条记录
                            sqlSugarClient.Insertable<SerialNum>(new SerialNum()
                            {
                                id = 1,
                                dateRule = "yymmdd",
                                sufWide = 4
                            }).ExecuteCommand();

                            sqlSugarClient.Insertable<SerialNum>(new SerialNum()
                            {
                                id = 2,
                                dateRule = "yymmdd",
                                sufWide = 5
                            }).ExecuteCommand();
                        }

                        MessageBox.Show("初始化DB完成，请修改init_DB设置，关闭初始化！！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                        MessageBox.Show("请删除现有数据库重试！", ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("请修改init_DB设置，关闭初始化！！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                System.Environment.Exit(0);
            }

            if (!System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "Plugins\\PIMS_WorkPlugin.dll"))
            {
                MessageBox.Show("Plugins\\PIMS_WorkPlugin.dll不存在！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                System.Environment.Exit(0);
            }

            Common.d = formLogView;

            string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");
            FileChanged fileChanged = new FileChanged(AppDomain.CurrentDomain.BaseDirectory + "Config/PIMSConfig.xml");
            if (File.Exists(configFile))
            {
                if (fileChanged.IsFileChanged() || !XmlHelper.IsValidXmlFile(configFile))
                {
                    File.Delete(configFile);
                }
            }

            if (File.Exists(configFile))
            {
                DeserializeDockContent ddc = new DeserializeDockContent(m_deserializeDockContent); // 放在后面的话会出错。
                //如果配置文件存在，就调用该函数，读取配置文件信息
                dockPanel1.LoadFromXml(configFile, ddc);
            }
            else
            {
                #region 实时日志
                formLogView.Show(dockPanel1, DockState.DockRight);
                
                #endregion

                #region PLC状态面板
                formPLCPanel1.Show(dockPanel1, DockState.DockLeft);
                #endregion

                #region 当前工单
                formCurrent.Show(dockPanel1, DockState.Document);
                #endregion

                #region 历史工单
                if (Common.pimsConfig.GetAppValueByKey("IsLoadFormHistory") == "1")
                {
                    formHistory.Show(dockPanel1, DockState.Document);
                }
                #endregion

                #region 生产记录(袋)
                if (Common.pimsConfig.GetAppValueByKey("IsLoadFormSavedDataBag") == "1")
                {

                    formSavedData.Show(dockPanel1, DockState.Document);
                }
                #endregion

                #region 生产记录(箱/托)
                if (Common.pimsConfig.GetAppValueByKey("IsLoadFormSavedData") == "1")
                {

                    formSavedDataBox.Show(dockPanel1, DockState.Document);
                }
                #endregion

                #region 历史日志查询
                formLogHistory.Show(dockPanel1, DockState.Document);
                #endregion
            }


            #region 离线打印
            if (Common.pimsConfig.GetAppValueByKey("IsLoadFormOfflinePrint") == "1")
            {
                离线打印ToolStripMenuItem.Enabled = true;
            }
            else
            {
                离线打印ToolStripMenuItem.Enabled = false;
               // 离线打印ToolStripMenuItem.Visible = false; //有BUG，与WeifenluoDock有冲突
            }
            #endregion

            #region 通过反射自动加载插件
            int plugCount = 1;
            foreach (PluginsInfo p in Common.pimsConfig.Plugin.add)
            {
                if (System.IO.File.Exists(basePath + p.fileName))
                {
                    if (p.IsDialog == 0)
                    {
                        try
                        {
                            ProxyObject po = new ProxyObject();
                            po.LoadFile(basePath + p.fileName);
                            // po.InvokeMethodShow(p.fullClassName, p.dispName, dockPanel1, DockState.Document);
                            po.InvokeMethodInitAndShow(p.fullClassName, p.dispName, Common.d, Common.log, Common.allPLC, dockPanel1, DockState.Document);
                        }
                        catch (Exception ex)
                        {
                            Common.log.Error("", ex);
                            Common.d.DebugMsg(ex.Message, InfoLevel.error);
                        }
                    }
                    else
                    {
                        ToolStripMenuItem toolMenu = null;
                        switch (plugCount)
                        {
                            case 1:
                                toolMenu = 插件1ToolStripMenuItem;
                                break;
                            case 2:
                                toolMenu = 插件2ToolStripMenuItem;
                                break;
                            case 3:
                                toolMenu = 插件3ToolStripMenuItem;
                                break;
                            case 4:
                                toolMenu = 插件4ToolStripMenuItem;
                                break;
                            case 5:
                                toolMenu = 插件5ToolStripMenuItem;
                                break;
                            case 6:
                                toolMenu = 插件6ToolStripMenuItem;
                                break;
                            case 7:
                                toolMenu = 插件7ToolStripMenuItem;
                                break;
                            case 8:
                                toolMenu = 插件8ToolStripMenuItem;
                                break;
                            case 9:
                                toolMenu = 插件9ToolStripMenuItem;
                                break;
                            case 10:
                                toolMenu = 插件10ToolStripMenuItem;
                                break;
                        }
                        if (toolMenu != null)
                        {
                            toolMenu.Tag = p;
                            toolMenu.Text = p.dispName;
                            toolMenu.Visible = true;
                            toolMenu.Click += ToolMenu_Click;

                            if (p.userLevel > 0)
                            {
                                toolMenu.Enabled = false;
                            }
                        }
                        plugCount++;
                    }

                }
            }
            #endregion

            Common.ActionUserChange = Action_UserChange;

            //切换至当前工单
            formCurrent.Activate();

        }

        private void dockPanel1_ActiveContentChanged(object sender, EventArgs e)
        {

        }

        
        /// <summary>
        /// 配置委托函数
        /// </summary>
        /// <param name="persistString"></param>
        /// <returns></returns>
        private static IDockContent GetContentFromPersistString(string persistString)
        {
            if (persistString == typeof(FormLogView).ToString())
            {
                return formLogView;
            }
            else if (persistString == typeof(FormPLCStatePanel).ToString())
            {
                return formPLCPanel1;
            }
            else if (persistString == typeof(FormMain).ToString())
                return formCurrent;
            else if (persistString == typeof(FormHistory).ToString())
                return formHistory;
            else if (persistString == typeof(FormSavedDataBag).ToString())
                return formSavedData;
            else if (persistString == typeof(FormSavedData).ToString())
                return formSavedDataBox; 
            else if (persistString == typeof(FormLogHistory).ToString())
                return formLogHistory;
            else
            {
                return null;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
            //this.exitMsg = ConfigurationManager.AppSettings["exitMsg"].ToString();
            this.exitMsg = Common.pimsConfig.GetAppValueByKey("exitMsg");
            this.consumer = Common.pimsConfig.GetAppValueByKey("consumer");
            this.plant = Common.pimsConfig.GetAppValueByKey("plant");
            if(String.IsNullOrEmpty(this.consumer))
            {
                //this.Text = String.Format("PIMS包装信息管理系统  软件版本:{0}", Common.ver);
                this.Text = String.Format("PIMS包装信息管理系统");
            }
            else
            {
                // this.Text = String.Format("{0} PIMS包装信息管理系统  软件版本:{1}", this.consumer, Common.ver);
                this.Text = String.Format("{0} PIMS包装信息管理系统", this.consumer);
            }
            
            Common.d.DebugMsg("PIMS启动！");
            Common.log.Info("PIMS启动！");

            //try
            //{
            //    Common.InitPLC();
            //}
            //catch(Exception ex)
            //{
            //    Common.log.Error("", ex);
            //    Common.d.DebugMsg(ex.Message);
            //}
            //切换到机器人1
            //formPLCPanel1.Activate();
        }

        /// <summary>
        /// 设置窗体最大化（不遮挡任务栏）显示全屏
        /// </summary>
        /// <param name="frm"></param>
        public virtual void SetFormMax(Form frm)
        {
            this.MaximumSize = new System.Drawing.Size(Screen.PrimaryScreen.WorkingArea.Width + 15, Screen.PrimaryScreen.WorkingArea.Height + 15);
        }

        private void FormContainer_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show(this.exitMsg, "Exit", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
            {
                e.Cancel = true;
            }
            else
            {
                Common.StopPLC();
                Common.d.DebugMsg("退出PIMS程序");
                Common.log.Info("退出PIMS程序");

                //系统退出前，保存当前的布局
                string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");
                dockPanel1.SaveAsXml(configFile);
            }
        }

        private void 打开网络连接ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string cmd = "shell32.dll,Control_RunDLL ncpa.cpl";
                Process process = Process.Start("rundll32", cmd);
                if (process != null)
                {
                    process.Dispose();
                }
            }
            catch
            {
            }
        }

        private void 打开工作PIMS工作目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string v_OpenFolderPath = AppDomain.CurrentDomain.BaseDirectory;
                System.Diagnostics.Process.Start("explorer.exe", "/e,\"" + v_OpenFolderPath + "\"");
            }
            catch
            {
            }
        }

        private void 打开命令提示符ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe"; //设定程序名
            p.StartInfo.UseShellExecute = false; //关闭Shell的使用
            p.StartInfo.RedirectStandardInput = false; //重定向标准输入
            p.StartInfo.RedirectStandardOutput = false; //重定向标准输出
            p.StartInfo.RedirectStandardError = false; //重定向错误输出
            p.StartInfo.CreateNoWindow = false; //设置不显示窗口
            p.Start();
            if (p != null)
            {
                p.Dispose();
            }
        }

        private void 数据字典ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Common.UserLogin.UserName == "Admin" || Common.UserLogin.Level == "9")
            {
                FormDataDictonary form = new FormDataDictonary();
                form.ShowDialog();
                form.Dispose();
            }
            else
            {
                MessageBox.Show("本操作需要管理员登陆！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }

        private void 离线打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //FormOfflinePrint form = new FormOfflinePrint();
            //form.ShowDialog();
            //form.Dispose();
        }

        private void 人工处理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //HandCreatOrder hand = new HandCreatOrder();
            //hand.StartPosition = FormStartPosition.CenterParent;
            //hand.ShowDialog();
            //String retMsg = hand.s;
            //MessageBox.Show(retMsg);
            //hand.Dispose();
        }

        private void 上级系统推送信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 在桌面创建快捷方式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                //实例化WshShell对象 
                WshShell shell = new WshShell();

                //通过该对象的 CreateShortcut 方法来创建 IWshShortcut 接口的实例对象 
                IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(
                    Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "//PIMS快捷方式.lnk");

                //设置快捷方式的目标所在的位置(源程序完整路径) 
                shortcut.TargetPath = System.Reflection.Assembly.GetExecutingAssembly().Location;

                //应用程序的工作目录 
                //当用户没有指定一个具体的目录时，快捷方式的目标应用程序将使用该属性所指定的目录来装载或保存文件。 
                shortcut.WorkingDirectory = System.Environment.CurrentDirectory;

                //目标应用程序窗口类型(1.Normal window普通窗口,3.Maximized最大化窗口,7.Minimized最小化) 
                shortcut.WindowStyle = 1;

                //快捷方式的描述 
                shortcut.Description = "ChinaDforce YanMang";

                //可以自定义快捷方式图标.(如果不设置,则将默认源文件图标.) 
                //shortcut.IconLocation = System.Environment.SystemDirectory + "\" + "shell32.dll, 165"; 

                //设置应用程序的启动参数(如果应用程序支持的话) 
                //shortcut.Arguments = "/myword /d4s"; 

                //设置快捷键(如果有必要的话.) 
                //shortcut.Hotkey = "CTRL+ALT+D"; 

                //保存快捷方式 
                shortcut.Save();

                MessageBox.Show("PIMS快捷方式创建成功！", "OK", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch(Exception ex)
            {
                Common.log.Error("", ex);
                MessageBox.Show(ex.Message,"NG",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

        private void Action_UserChange(string userlevel)
        {
            int level;
            int.TryParse(userlevel, out level);
            EnableToolMenu(插件1ToolStripMenuItem, level);
            EnableToolMenu(插件2ToolStripMenuItem, level);
            EnableToolMenu(插件3ToolStripMenuItem, level);
            EnableToolMenu(插件4ToolStripMenuItem, level);
            EnableToolMenu(插件5ToolStripMenuItem, level);
            EnableToolMenu(插件6ToolStripMenuItem, level);
            EnableToolMenu(插件7ToolStripMenuItem, level);
            EnableToolMenu(插件8ToolStripMenuItem, level);
            EnableToolMenu(插件9ToolStripMenuItem, level);
            EnableToolMenu(插件10ToolStripMenuItem, level);
        }

        private void EnableToolMenu(ToolStripMenuItem toolMenu, int currentLevel)
        {
            if (toolMenu.Visible)
            {
                PluginsInfo pluginsInfo = (PluginsInfo)toolMenu.Tag;
                bool flag = false;
                if (currentLevel >= pluginsInfo.userLevel)
                {
                    flag = true;
                }
                else
                {
                    flag = false;
                }
                this.Invoke(
                  new Action(() => {
                      toolMenu.Enabled = flag;
                  }));
            }
        }

        private void ToolMenu_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem toolMenu = (ToolStripMenuItem)sender;
            PluginsInfo pluginsInfo = (PluginsInfo)toolMenu.Tag;

            try
            {
                Assembly assemWorkPlugin = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + pluginsInfo.fileName);
                Type t = assemWorkPlugin.GetType(pluginsInfo.fullClassName);
                object obj = Activator.CreateInstance(t, null);
                t.InvokeMember("Init", BindingFlags.InvokeMethod, null, obj, new object[] { Common.d, Common.log });
                t.InvokeMember("ShowDialog", BindingFlags.InvokeMethod, null, obj, new object[] { });
                t.InvokeMember("Close", BindingFlags.InvokeMethod, null, obj, new object[] { });
                t.InvokeMember("Dispose", BindingFlags.InvokeMethod, null, obj, new object[] { });
            }
            catch (Exception ex)
            {
                Common.log.Error("", ex);
                MessageBox.Show(ex.Message, "NG", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
